package com.chenfei.sharding.jdbc.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * @author chenfei
 * @description
 * @since 2018/2/26
 */
@RestController
@Slf4j
public class SessionController {

    @RequestMapping(value="/main", method= RequestMethod.GET)
    public String main(HttpServletRequest request) {
        log.info("session begin");
        HttpSession session = request.getSession();
        String sessionId = (String) session.getAttribute("sessionId");
        // sessionId不为空
        if (null != sessionId) {
            System.out.println("main sessionId:" + sessionId);
            return "main";
        } else { // sessionId为空
            return "redirect:/login";
        }
    }

    @RequestMapping(value="/login", method= RequestMethod.POST)
    public String doLogin(HttpServletRequest request) {
        System.out.println("I do real login here");
        HttpSession session = request.getSession();
        String sessionId = UUID.randomUUID().toString();
        session.setAttribute("sessionId", sessionId);
        System.out.println("login sessionId:" + sessionId);
        return "redirect:/main";
    }
}
